//
//  ExamSignPrimeViewController.m
//  CommunityNannyO2O
//
//  Created by 90 on 15/7/21.
//  Copyright (c) 2015年 Apple. All rights reserved.
//

#import "ExamSignPrimeViewController.h"
#import "AppConfig.h"
#import "QXNetWorkTool.h"
#import "APIAdress.h"
#import "MBProgressHUD+YC.h"
#import "MJExtension.h"
#import "AccountTool.h"
#import "PrimeSignUpTableViewCellFirst.h"
#import "PrimeSignUpTableViewCellSecond.h"
#import "PrimeSignUpTableViewCellZero.h"
#import "SelectExamLevelView.h"
#import "ExamGuideViewController.h"
#import "ExamCourseViewController.h"
#import "SelectExamTimeSignUpView.h"
#import "SelectExamPlaceViewController.h"
#import "UserDataSingleton.h"
#import "SelectMonthAndDayCell.h"
#import "SelectExamTiemModel.h"
#import "CommFunc.h"

@interface ExamSignPrimeViewController()<QXNetWorkToolDelegate,
        UITableViewDataSource,UITableViewDelegate,
        LevelDeletage,SelectExamLevelDeletage,
        CourseDeletage,SelectExamCourseViewDeletage,
        SelectExamePlaceDeletage,ExamPlaceDeletage,
        SelectMonthAndDayCellDeletage>
{

}

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSMutableArray *data;
@property (strong, nonatomic) NSMutableArray *musicBaselevelData;
@property (nonatomic, copy) NSString *examLevel;
@property (nonatomic, copy) NSString *examCourse;
@property (nonatomic, copy) NSString *examCourseId;
@property (nonatomic, copy) NSString *place;
@property (nonatomic, copy) NSString *placeId;
@property (nonatomic, copy) NSString *year;
@property (nonatomic, copy) NSString *month;
@property (nonatomic, copy) NSString *day;
@property (strong, nonatomic) PrimeSignUpTableViewCellZero  *cellZero;

@end


@implementation ExamSignPrimeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.dataSource = self;
    
    self.tableView.delegate = self;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.data = [NSMutableArray arrayWithObjects:@"等级1", @"等级2", @"等级3", @"等级4",@"等级5",@"等级6", @"等级7", @"等级8", @"等级9",nil];
    
    self.musicBaselevelData = [NSMutableArray arrayWithObjects:@"等级1", @"等级2", @"等级3", nil];
    
    self.examLevel = @"等级1";
    
    self.year = @"2015年";
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)    //second cell
    {
        return 91;
    }
    else if (indexPath.row == 1)    //thirth cell
    {
        return 68;
    }
    else if (indexPath.row == 2)    //fourth cell
    {
        if (self.cellZero)
        {   
            int height = [CommFunc sizeWithString:self.cellZero.adress.text
                                       font:[UIFont fontWithName:@"Hiragino Sans GB" size:15]
                                        max:CGSizeMake(self.cellZero.adress.frame.size.width, MAXFLOAT)].height;
            
            if (height <= 90)
                return 90;
            else
            {
                height = 30 + self.cellZero.adress.frame.origin.y + height + 5;
                return height;
            }
        }
    }
    else if (indexPath.row == 3)    // cell
    {
        return 343;
    }
    return 50;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0)
    {
        PrimeSignUpTableViewCellFirst *cell = [PrimeSignUpTableViewCellFirst cellWithTableView:tableView];
        cell.courseDeletage = self;
        
        if (self.examCourse == nil || [self.examCourse isEqualToString:@""])
        {
            if ([[UserDataSingleton shareInstance].currSelectExamKind isEqualToString:[UserDataSingleton shareInstance].quiTa])
            {
                self.examCourse = @"电吉他";
                self.examCourseId = [UserDataSingleton shareInstance].quiTa;
            }
            if ([[UserDataSingleton shareInstance].currSelectExamKind isEqualToString:[UserDataSingleton shareInstance].JazzDrum])
            {
                self.examCourse = @"爵士鼓";
                self.examCourseId =[UserDataSingleton shareInstance].JazzDrum;
            }
            if ([[UserDataSingleton shareInstance].currSelectExamKind isEqualToString:[UserDataSingleton shareInstance].bass])
            {
                self.examCourse = @"电贝司";
                self.examCourseId =[UserDataSingleton shareInstance].bass;
            }
            if ([[UserDataSingleton shareInstance].currSelectExamKind isEqualToString:[UserDataSingleton shareInstance].musicBase])
            {
                self.examCourse = @"音乐理论";
                self.examCourseId =[UserDataSingleton shareInstance].musicBase;
            }
        }
        
        cell.lession.text = self.examCourse;
        return cell;
    }
    else if (indexPath.row == 1)
    { 
        PrimeSignUpTableViewCellSecond *cell = [PrimeSignUpTableViewCellSecond cellWithTableView:tableView];
        cell.levelDelegate = self;
        cell.level.text = [self getLevel:self.examLevel];
        [self resetNewExamLevel:self.examLevel];
        return cell;
    }
    else if (indexPath.row == 2)
    {
        PrimeSignUpTableViewCellZero *cell = [PrimeSignUpTableViewCellZero cellWithTableView:tableView];
        cell.selectExamePlaceDeletage = self;
        
        cell.adress.text = self.place;
        cell.adress_id = self.placeId;
        
        self.cellZero = cell;
        
        return cell;
    }
    else if (indexPath.row == 3)
    {
        SelectMonthAndDayCell *cell = [SelectMonthAndDayCell cellWithTableView:tableView];
        cell.delegate = self;
        
        [cell initMenu];
        
        return cell;
    }
    
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    
    return cell;
}

-(void)configNavigationItem
{
    self.navigationItem.title = @"报名";
    [self.navigationController.navigationBar setTranslucent:NO];
    
    [self.navigationController.navigationBar
     setBackgroundImage:[UIImage imageNamed:@"bg_navigation_bar"]
     forBarMetrics:UIBarMetricsDefault];
    
    //status bar的字体为白色
    //导航栏的背景色是黑色
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],NSFontAttributeName,nil]];
    
    [self configNavigationBackAction:^{
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

-(void)useMethodToFindBlackLineAndHind
{
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    blackLineImageView.hidden = YES;
}

-(void)didSelectLevel
{
    SelectExamLevelView *obj = [SelectExamLevelView create];
    obj.view.backgroundColor = [UIColor clearColor];
    obj.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    obj.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    obj.definesPresentationContext = YES;
    obj.selectExamlevelDelegate = self;
    
    if ([[UserDataSingleton shareInstance].musicBase isEqualToString:self.examCourseId])
    {
        obj.isMusicBase = YES;
        [obj setLevelData:self.musicBaselevelData];
    }
    else
    {
        obj.isMusicBase = NO;
        [obj setLevelData:self.data];
    }
    
    [self presentViewController:obj animated:YES completion:nil];
}

-(void)setLevel:(NSString *)str
{
    self.examLevel = str;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    NSArray *indexArray = [NSArray arrayWithObject:indexPath];
    
    [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
}

-(void)didSelectCourse
{
    ExamCourseViewController *obj = [ExamCourseViewController create];
    obj.selectExamCourseDelegate = self;
    [self.navigationController pushViewController:obj animated:YES];
}

-(void)setSelectExamCourse:(NSString *)str majorId:(NSString *)mId
{
    self.examCourse = str;
    self.examCourseId = mId;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0
                                                inSection:0];
    
    NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:1
                                                inSection:0];
    
    NSArray *indexArray = [NSArray arrayWithObjects:indexPath, indexPath2, nil];
    
    [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
}

-(void)selectExamPlace
{
    SelectExamPlaceViewController *obj = [SelectExamPlaceViewController create];
    obj.delegate = self;
    
    [self.navigationController pushViewController:obj animated:YES];
}

-(void)setExamPlace:(NSString *)str Id:(NSString *)id
{
    self.place = str;
    self.placeId = id;
    
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:2 inSection:0]]
                          withRowAnimation:UITableViewRowAnimationNone];
}

-(void)selectYear:(NSString*)year
{
    self.year = year;
}

-(void)selectMonth:(NSString*)month Day:(NSString*)day
{
    self.month = month;
    self.day = day;
    
    [self selectTime];
}

- (void)selectTime
{
    UserDataSingleton *userData = [UserDataSingleton shareInstance];
    if(![userData isLogin])
    {
        [userData pleaseLogin:self];
        return;
    }
    
    if (self.examCourse == nil || [self.examCourse isEqualToString:@""]
        || self.examCourseId == nil || [self.examCourseId isEqualToString:@""])
    {
        [MBProgressHUD showError:@"请选择考试科目"];
        return;
    }
    
    if (self.examLevel == nil || [self.examLevel isEqualToString:@""])
    {
        [MBProgressHUD showError:@"请选择考试等级"];
        return;
    }
    
    if (self.place == nil || [self.place isEqualToString:@""])
    {
        [MBProgressHUD showError:@"请选择考试地点"];
        return;
    }
    
    if (self.month == nil || [self.month isEqualToString:@""]
        || self.day == nil || [self.day isEqualToString:@""])
    {
        [MBProgressHUD showError:@"请选择考试日期"];
        return;
    }
    
    userData.examLevel = [self.examLevel substringWithRange:NSMakeRange(2, 1)];
    userData.examCourse = self.examCourse;
    userData.examCourseId = self.examCourseId;
    userData.place = self.place;
    userData.placeId = self.placeId;
    userData.year = [self.year substringWithRange:NSMakeRange(0, 4)];
    userData.month = self.month;
    userData.day = self.day;
    
    
    
    NSDate *now = [NSDate date];
  
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    
    NSInteger hour = [dateComponent hour];
    NSInteger minute = [dateComponent minute];
    NSInteger second = [dateComponent second];

    
    NSString * timeStr = [NSString stringWithFormat:@"%02d%02d%02d%02d%02d%02d",userData.year.intValue,userData.month.intValue,userData.day.intValue,hour,minute,second];

    if ([self checkTime:timeStr]) {
        

        return;
        
    }
    
    
    [MBProgressHUD showMessage:@"正在加载"];
    
    QXNetWorkTool *QXnetWorkTool = [[QXNetWorkTool alloc]init];
    
    QXnetWorkTool.QXNetWorkDelegate = self;
    
    [QXnetWorkTool GetDataFromServerWithPostMethodandInterfaceName:VerificationExamProfessionalLevelInterface andParameter:
     @[@{@"user_id":userData.user_id,
         @"major_id":userData.examCourseId,
         @"grade_num":userData.examLevel}] tag:1];
}

- (void)GetFailResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUD];
    
    if (Response == nil)
        return;
    
    NSString *message = Response;
    
    [MBProgressHUD showError:message];
    
}

- (void)GetSuccessMessage:(id)message andTag:(int)tag
{
//    [MBProgressHUD hideHUD];
    
    NSString *mes = message;
    
    switch (tag)
    {
        case 1:
//            [MBProgressHUD showSuccess:mes];
            break;
    }
}

-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUD];
    
    if (Response == nil)
    {
        return;
    }
    
    switch (tag)
    {
        case 1:
        {
            NSString *tmpMonth;
            NSString *tmpDay;
            if ([self.month intValue] < 10)
            {
                tmpMonth = [NSString stringWithFormat:@"0%@", self.month];
            }
            else
            {
                tmpMonth = self.month;
            }
            
            if ([self.day intValue] < 10)
            {
                tmpDay = [NSString stringWithFormat:@"0%@", self.day];
            }
            else
            {
                tmpDay = self.day;
            }
            
            self.year = [self.year substringWithRange:NSMakeRange(0, 4)];
            
            NSString *time = [NSString stringWithFormat:@"%@-%@-%@",self.year,
                              tmpMonth, tmpDay];
            
            [MBProgressHUD showMessage:@"正在加载"];
            QXNetWorkTool *QXnetWorkTool = [[QXNetWorkTool alloc]init];
            
            QXnetWorkTool.QXNetWorkDelegate = self;
        
            [QXnetWorkTool GetDataFromServerWithPostMethodandInterfaceName:GetExamTimeInterface andParameter:
             @[@{@"exam_date":time,
                 @"exam_site_id":[UserDataSingleton shareInstance].placeId}]
                                                                       tag:2];
            break;
        }
        case 2:
        {
            NSMutableArray *data = [[NSMutableArray alloc] init];
            for (NSDictionary *dic in Response)
            {
                SelectExamTiemModel *model =
                        [SelectExamTiemModel SelectExamTimeWithDict:dic];
                
                [data addObject:model];
            }
            
            SelectExamTimeSignUpView *obj = [SelectExamTimeSignUpView create];
            obj.timeData = data;
            [self.navigationController pushViewController:obj animated:YES];
            break;
        }
    }
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self configNavigationItem];

    [self useMethodToFindBlackLineAndHind];
}

-(void)viewWillDisappear:(BOOL)animated
{

}


- (BOOL)checkTime:(NSString *)timeStr {


    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
   
    [date setDateFormat:@"yyyyMMddHHmmss"];
    
    NSDate *d=[date dateFromString:timeStr];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
   
    NSTimeInterval now=[dat timeIntervalSince1970]*1 + 60 * 60 *24 * 3;
   
    
    
    if (now < late){
      
    
        return NO;
     
    }else{
    
        NSCalendar *calendar = [NSCalendar currentCalendar];
      
        NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
        
        [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_cn"]];
        
        [inputFormatter setDateFormat:@"yyyy年MM月dd日"];
        
        
        NSDate *nextDate = [NSDate dateWithTimeInterval:3*24*60*60 sinceDate:dat];
        
        NSDateComponents *comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekday|NSCalendarUnitDay fromDate:nextDate];
        
        NSString * str = [inputFormatter stringFromDate:nextDate];
        
        NSString * error = [NSString stringWithFormat:@"请选择%@以后的时间",str];
        
        
        [MBProgressHUD showError:error];
        
        return YES;
    
    }
    
}

- (NSString *)getLevel:(NSString *)level
{
    if ([[UserDataSingleton shareInstance].musicBase isEqualToString:self.examCourseId])
    {
        if ([level isEqualToString:@"等级1"])
        {
            return @"初级";
        }
        else if ([level isEqualToString:@"等级2"])
        {
            return @"中级";
        }
        else if ([level isEqualToString:@"等级3"])
        {
            return @"高级";
        }
        else
        {
            return @"初级";
        }
    }
    
    return level;
}

- (void)resetNewExamLevel:(NSString *)level
{
    self.examLevel = level;
    
    if ([[UserDataSingleton shareInstance].musicBase isEqualToString:self.examCourseId])
    {
        if ([level isEqualToString:@"等级1"])
        {
            self.examLevel = level;
        }
        else if ([level isEqualToString:@"等级2"])
        {
            self.examLevel = level;
        }
        else if ([level isEqualToString:@"等级3"])
        {
            self.examLevel = level;
        }
        else
        {
            self.examLevel = @"等级1";
        }
    }
}

@end


















